<template>
  <main-box>
    <PlusSearch
      v-model="queryform"
      :columns="formConfig"
      :show-number="2"
      label-width="80"
      label-position="right"
      class="mb-xs"
      @search="initData()"
      @reset="handleRest()"
    >
      <template #plus-field-type>
        <el-radio-group v-model="queryform.type">
          <el-radio-button label="全部" :value="-1" />
          <el-radio-button label="借出" :value="1" />
          <el-radio-button label="归还" :value="2" />
        </el-radio-group>
      </template>
      <template #plus-field-warehouseId>
        <chooseWarehouse v-model="queryform.warehouseId" />
      </template>
    </PlusSearch>
    <div class="mb-2">
      <btnExport
        :exportApi="exportApi"
        :queryform="getQueryParam()"
        download-name="借还记录"
      />
    </div>
    <PureTable
      ref="tableRef"
      border
      adaptive
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :pagination="pagination"
      @page-size-change="initData()"
      @page-current-change="initData(false)"
    >
      <template #action="{ row }">
        <el-link
          class="ml-1"
          type="primary"
          :underline="false"
          @click="handleDetail(row)"
          >详情</el-link
        >
        <el-link
          v-if="row.mediaUrl"
          type="success"
          :underline="false"
          class="ml-1 mr-1"
          @click="handlePreview(row)"
          >视频</el-link
        >
        <div v-if="row.picUrl" class="relative" style="display: inline-block">
          <el-image
            :src="row.picUrl"
            :preview-src-list="[row.picUrl]"
            :preview-teleported="true"
            class="absolute"
            style="
              width: 100%;
              height: 100%;
              top: 0;
              position: absolute !important;
              z-index: 100;
              opacity: 0;
            "
          >
            <template #placeholder>
              <div style="cursor: wait; width: 100%; height: 100%" />
            </template>
            <template #error>
              <div
                style="cursor: pointer"
                @click="ElMessage.error(`图片加载失败-${row.picUrl}`)"
              >
                加载失败
              </div>
            </template>
          </el-image>
          <el-link :underline="false" type="primary" class="ml-1 mr-1">
            图像
          </el-link>
        </div>
      </template>
    </PureTable>
    <detail-info ref="detailInfoRef" />
    <preview ref="previewRef" />
  </main-box>
</template>

<script setup lang="tsx">
import { ref } from "vue";
import { useTableConfig } from "@/utils/tableConfig";
import { type PlusColumn, PlusSearch } from "plus-pro-components";
import { useRouter } from "vue-router";

import btnExport from "@/components/btnExport/index.vue";
import detailInfo from "./modules/detail-info.vue";
import preview from "./modules/preview.vue";
import { listApi, exportApi } from "@/api/record/list";
import { diffDate } from "@/utils";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import chooseWarehouse from "@/components/choose-warehouse/index.vue";
import dict from "@/utils/dict";
import { ElMessage } from "element-plus";

/* 查询表单 */
const formConfig: PlusColumn[] = [
  {
    label: "发生时间",
    prop: "time",
    valueType: "date-picker",
    fieldProps: {
      type: "daterange",
      valueFormat: "YYYY-MM-DD"
    }
  },
  {
    label: "事件类型",
    prop: "type"
  },
  {
    label: "工具室",
    prop: "warehouseId"
  },
  {
    label: "查询",
    prop: "searchValue",
    fieldProps: { placeholder: "名称/编号/分类/型号" }
  }
];
const queryform = ref({
  type: -1,
  time: [] as any,
  searchValue: "",
  warehouseId: ""
});
const handleRest = () => {
  initData(true);
  queryform.value.type = -1;
};

const getQueryParam = () => {
  const params = { ...queryform.value } as any;
  if (params.type == -1) {
    params.type = "";
  }
  if (params.time && params.time.length) {
    params.params = {
      startTime: queryform.value.time[0],
      endTime: queryform.value.time[1]
    };
  }
  delete params.time;
  return params;
};

/* 表格数据 */
const { pagination } = useTableConfig();
const tableData = ref([]);
const loading = ref(false);
const columns = [
  {
    label: "物件图片",
    prop: "picUrl",
    cellRenderer: ({ row }) => {
      const { picUrl } = row.tool;
      let list = [];
      if (picUrl) {
        list = picUrl.split(",");
      }
      return list.map((item, index) => {
        return (
          <el-image
            src={item}
            width={50}
            initial-index={index}
            preview-src-list={list}
            preview-teleported={true}
          />
        );
      });
    }
  },
  { label: "物件编号", prop: "tool.code" },
  { label: "物件名称", prop: "tool.name" },
  { label: "分类", prop: "tool.toolCategoryName" },
  { label: "物件型号", prop: "tool.modelName" },
  { label: "标签编号", prop: "tool.labelCode" },
  { label: "工具室", prop: "tool.warehouseName" },
  { label: "存放位置", prop: "tool.storageLocation" },
  {
    label: "库存状态",
    prop: "storageState",
    cellRenderer: ({ row }) => {
      const { tool } = row;

      const target = dict.storageState(tool.storageState);
      return <el-tag type={target.type}>{target.name}</el-tag>;
    }
  },
  {
    label: "借还类型",
    prop: "type",
    cellRenderer: ({ row }) => {
      // const { type } = row;
      const type = Number(row.type);
      const col = type == 1 ? "warning" : "success";
      const txt = type == 1 ? "借出" : "归还";
      return <el-tag type={col}>{txt}</el-tag>;
    }
  },
  {
    label: "发生时间",
    prop: "lendTime",
    formatter: row => {
      if (row.type == 1) {
        return row.lendTime;
      } else {
        return row.returnTime;
      }
    },
    width: 160
  },
  {
    label: "用户",
    prop: "nickName",
    formatter: ({ nickName, userName }) => nickName || userName
  },
  {
    label: "使用时长",
    prop: "useTime",
    formatter: ({ isReturn, lendTime, returnTime }) => {
      // 未归还:当前时间-借出时间 0
      // 己归还: 归还时间 - 借出时间 1
      return diffDate(lendTime, Number(isReturn) ? returnTime : null);
    },
    width: 180
  },
  { label: "操作", prop: "action", fixed: "right", slot: "action", width: 100 }
];

/* 数据 */
const initData = (needInit = true) => {
  loading.value = true;
  if (needInit) {
    pagination.currentPage = 1;
  }
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    ...getQueryParam()
  } as any;

  listApi(params)
    .then(res => {
      tableData.value = res.rows;
      pagination.total = Number(res.total);
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

initData();

/* 列表操作 */
const router = useRouter();
const goDetail = row => {
  const query = {
    path: "/tools/detail",
    query: { id: String(row.tool.toolId) },
    name: "ToolDetailIndex"
  };
  useMultiTagsStoreHook().handleTags("push", {
    ...query,
    meta: {
      title: "工具详情",
      dynamicLevel: 1
    }
  });
  router.push(query);
};

const detailInfoRef = ref<any>();
const handleDetail = row => {
  detailInfoRef.value.show(row);
};

/* 查看 */
const previewRef = ref(null);
const handlePreview = row => {
  previewRef.value.show(row);
};

const imgError = (el: any) => {
  console.log(el);
  el.style.display = "none";
};
</script>
